package Demo5;


import java.util.PriorityQueue;
import java.util.TimerTask;

class MyTimertask_1 implements Comparable<MyTimertask_1>{
    private Runnable task;
    private long time;

    public MyTimertask_1(Runnable task, long time) {
        this.task = task;
        this.time = time;
    }

    public long getTime() {
        return this.time;
    }

    public void run(){
        task.run();
    }
    @Override
    public int compareTo(MyTimertask_1 o) {
        return (int)(this.time-o.time);
    }
}

class Mytimer_1{
   private Object lock=new Object();

   private PriorityQueue<MyTimertask_1> queue=new PriorityQueue<>();

    public void schedule(Runnable task,long delay){
        synchronized (lock){
            MyTimertask_1 timertask=new MyTimertask_1(task,System.currentTimeMillis()+delay);
            queue.offer(timertask);
            lock.notify();
        }
    }

    public Mytimer_1() {
            Thread t=new Thread(()->{
                try {
                while(true){
                    synchronized (lock) {
                        while (queue.isEmpty()) {
                            lock.wait();
                        }
                        MyTimertask_1 timertask=queue.peek();
                        if(System.currentTimeMillis()< timertask.getTime()){
                            lock.wait(timertask.getTime()-System.currentTimeMillis());
                        }else {
                            timertask.run();
                            queue.poll();
                        }
                    }
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            });
      t.start();
    }
}


public class Main17 {
    public static void main(String[] args) {
        Mytimer_1 mytimer=new Mytimer_1();
        mytimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 3000");
            }
        }, 3000);

        mytimer.schedule(new TimerTask() {
            @Override
            public void run() {
                System.out.println("hello 2000");
            }
        }, 2000);

        mytimer.schedule(new TimerTask() {
            @Override
            public void run() {
                System.out.println("hello 1000");
            }
        }, 1000);

        System.out.println("hello main");

    }
}
